<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactStage\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Event\DeleteContactRawEvent;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Plugin\ContactStage\Logic\ContactStageEmployeeUpdateLogic;
use Psr\Container\ContainerInterface;

/**
 * 拉黑用户监听，触发阶段更改.
 *
 * @Listener(priority=9999)
 */
class DeleteContactRawListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 客户表.
     * @Inject
     * @var WorkContactContract
     */
    private $workContactService;

    /**
     * @Inject
     * @var CorpContract
     */
    private $corpService;

    /**
     * 员工表.
     * @Inject
     * @var WorkEmployeeContract
     */
    private $workEmployeeService;

    /**
     * @Inject
     * @var ContactStageEmployeeUpdateLogic
     */
    private $contactStageEmployeeUpdateLogic;

    public function listen(): array
    {
        return [
            DeleteContactRawEvent::class,
        ];
    }

    public function process(object $event)
    {
        try {
            $message = $event->message;
            Db::beginTransaction();
            try {
                // 阶段自动化
                if (! isset($message['UserID'], $message['ExternalUserID'])) {
                    return;
                }

                // 查询客户id,查询员工id
                [$contactId, $employeeId, $corpId] = $this->employeeAndContactData($message['ToUserName'], $message['UserID'], $message['ExternalUserID']);
                if ($contactId === 0 || $employeeId === 0 || $corpId === 0) {
                    return;
                }

                $this->contactStageEmployeeUpdateLogic->handle($contactId, $employeeId, $corpId);
                Db::commit();
            } catch (\Throwable $e) {
                Db::rollBack();
                $this->logger->error($e->getTraceAsString());
                throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
            }
        } catch (\Exception $e) {
            $this->logger->error(sprintf('[客户阶段]失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }

    /**
     * 获取员工与客户ID.
     * @param string $wxUserId ...
     * @param string $wxContactUserId ...
     * @return array ...
     */
    protected function employeeAndContactData(string $wxCorpId, string $wxUserId, string $wxContactUserId): array
    {
        $contactId = 0;
        $employeeId = 0;
        $contactInfo = $this->workContactService->getWorkContactByWxExternalUserId($wxContactUserId, ['id', 'unionid']);
        if (! empty($contactInfo)) {
            $contactId = $contactInfo['id'];
        }

        $corp = $this->corpService->getCorpByWxCorpId($wxCorpId, ['id']);

        if (empty($corp)) {
            return [$contactId, $employeeId];
        }

        $employeeInfo = $this->workEmployeeService->getWorkEmployeeByWxUserIdCorpIdWithTrashed($wxUserId, (int) $corp['id'], ['id']);
        if (! empty($employeeInfo)) {
            $employeeId = $employeeInfo['id'];
        }

        return [$contactId, $employeeId, empty($corp['id']) ? 0 : $corp['id']];
    }
}
